package org.csu.mypetstore_ssm.service;

import org.csu.mypetstore_ssm.domain.Category;
import org.csu.mypetstore_ssm.domain.Item;
import org.csu.mypetstore_ssm.domain.Product;
import org.csu.mypetstore_ssm.persistence.CategoryMapper;
import org.csu.mypetstore_ssm.persistence.ItemMapper;
import org.csu.mypetstore_ssm.persistence.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CatalogService {

    @Autowired
    private final CategoryMapper categoryMapper;

    @Autowired
    private final ProductMapper productMapper;

    @Autowired
    private final ItemMapper itemMapper;

    public CatalogService(CategoryMapper categoryMapper, ProductMapper productMapper, ItemMapper itemMapper) {
        this.categoryMapper = categoryMapper;
        this.productMapper = productMapper;
        this.itemMapper = itemMapper;
    }

    public Category getCategory(String categoryId){
        return categoryMapper.getCategory(categoryId);
    }
    public List<Category> getCategoryList() {
        return categoryMapper.getCategoryList();
    }

    public Product getProduct(String productId) {
        return productMapper.getProduct(productId);
    }
    public List<Product> getProductListByCategory(String categoryId) {
        return productMapper.getProductListByCategory(categoryId);
    }
    // TODO enable using more than one keyword
    public List<Product> searchProductList(String keyword) {
        return productMapper.searchProductList("%"+keyword.toLowerCase()+"%");
    }
    public List<Item> getItemListByProduct(String productId) {
        return itemMapper.getItemListByProduct(productId);
    }

    public Item getItem(String itemId) {
        return itemMapper.getItem(itemId);
    }

    public boolean isItemInStock(String itemId) {
        return itemMapper.getInventoryQuantity(itemId) > 0;
    }

    public void reduceItemQuantity(String itemId, int quantity) {
        System.out.println("减少库存: itemId={}, quantity={}"+itemId+quantity);
        Item item = itemMapper.getItem(itemId);
        if (item != null) {
            int newQuantity = item.getQuantity() - quantity;
            if (newQuantity >= 0) {
                item.setQuantity(newQuantity);
                itemMapper.updateItem(item); // 更新库存
            } else {
                throw new RuntimeException("库存不足，无法完成订单");
            }
        } else {
            throw new RuntimeException("商品不存在");
        }
    }

    public int getInventoryQuantity(String itemId) {
        return itemMapper.getInventoryQuantity(itemId);
    }

//    public void reduceItemQuantity(String itemId, int quantity){
//
//    }; // 减少库存

    public void removeById(String itemId){
//        itemMapper.
    }
}